// 格式化价格
export const formatPrice = (price) => {
  if (typeof price !== 'number') {
    return '0.00';
  }
  return price.toFixed(2);
};

// 格式化数量
export const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万';
  }
  return num.toString();
};

// 节流函数
export const throttle = (fn, delay = 500) => {
  let timer = null;
  return function(...args) {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 防抖函数
export const debounce = (fn, delay = 500) => {
  let timer = null;
  return function(...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 显示消息提示框
export const showToast = (title, icon = 'none') => {
  uni.showToast({
    title,
    icon
  });
};

// 显示模态弹窗
export const showModal = (content, title = '提示', showCancel = true) => {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      showCancel,
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else if (res.cancel) {
          resolve(false);
        }
      },
      fail: () => {
        reject(new Error('模态框显示失败'));
      }
    });
  });
};

// 页面跳转
export const navigateTo = (url) => {
  uni.navigateTo({
    url
  });
};

// 页面重定向
export const redirectTo = (url) => {
  uni.redirectTo({
    url
  });
};

// 页面返回
export const navigateBack = (delta = 1) => {
  uni.navigateBack({
    delta
  });
};

// 跳转到tabBar页面
export const switchTab = (url) => {
  uni.switchTab({
    url
  });
}; 